package org.example.oauth2.client;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
public class HelloController {

    @Autowired
    RestTemplate restTemplate;

    @GetMapping("/index.html")
    public String hello() {
        return "index";
    }

    /**
     * 在登录接口中，当收到一个用户名密码之后，我们通过 RestTemplate 发送一个 POST 请求，
     * 注意 post 请求中，grant_type 参数的值为 password，通过这个请求，我们可以获取 auth-server 返回的 access_token，格式如下：
     * {access_token=02e3a1e1-925f-4d2c-baac-42d76703cae4, token_type=bearer, refresh_token=836d4b75-fe53-4e41-9df1-2aad6dd80a5d, expires_in=7199, scope=all}
     */
    @PostMapping("/login")
    public String login(String username,String password,Model model){
        LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("username",username);
        map.add("password",password);
        map.add("client_id","clientId_1");
        map.add("client_secret","secret_1");
        map.add("grant_type","password");
        // 通过用户名密码在第三方直接向认证服务器获取令牌
        Map<String,String> resp = restTemplate.postForObject("http://localhost:8081/oauth/token", map, Map.class);
        System.out.println("resp：" + resp);
        String accessToken = resp.get("access_token");
        System.out.println("accessToken：" + accessToken);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization","Bearer " + accessToken);
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        // 将令牌放在请求头中，去资源服务器获取资源
        ResponseEntity<String> responseEntity = restTemplate.exchange("http://localhost:8082/admin/hello", HttpMethod.GET, httpEntity, String.class);
        model.addAttribute("msg",responseEntity.getBody());
        return "index";
    }
}
